package com.wdciti.sccp.iot.springvertx.protocols.tcp;

import com.wdciti.sccp.iot.springvertx.EndPointVerticle;
import com.wdciti.sccp.iot.springvertx.protocols.tcp.ext.EndpointHeadersAdaptor;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.buffer.Buffer;
import lombok.extern.slf4j.Slf4j;

import java.time.Instant;

/**
 * @author by early
 */
@Slf4j
//@VerticleBean(isWorker = false)
public class DumpHexVerticle extends AbstractVerticle {

    @Override
    public void start() {
        vertx.eventBus().<Buffer>consumer(EndPointVerticle.getDumpAddr()).handler(msg -> {
            EndpointHeadersAdaptor adaptor = EndpointHeadersAdaptor.instanceFrom(msg.headers());
            log.info(printHex(adaptor, msg.body()));
        });
//        vertx.eventBus().consumer(EndPointVerticle.getDumpAddr()).handler(msg -> {
//            String addr = msg.headers().get(EndpointHeadersAdaptor.BUS_ADDR);
//            vertx.eventBus().<Buffer>consumer(addr + EndPointVerticle.DUMP).handler(hd -> {
//                try {
//                    EndpointHeadersAdaptor adaptor = EndpointHeadersAdaptor.instanceFrom(hd.headers());
//                    log.info(printHex(adaptor, hd.body()));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }).exceptionHandler(Throwable::printStackTrace);
//        });

    }

    private String printHex(EndpointHeadersAdaptor adaptor, Buffer body) {
        String id = adaptor.getBusAddr().replace(EndPointVerticle.PROTOCOL, "") + "(" + adaptor.getBusAddrTail() + ")";
        String remote = "[" + adaptor.getRemoteAddress() + "]";
        String local = "[" + adaptor.getLocalAddress() + "]";
        ByteBuf buffer = body.getByteBuf();
        String arrow = "---";
        if (adaptor.getRorS().equals(EndpointHeadersAdaptor.RS.R)) {
            arrow = "--->";
        } else if (adaptor.getRorS().equals(EndpointHeadersAdaptor.RS.S)) {
            arrow = "<---";
        }
//        Date date = Date.from(Instant.ofEpochSecond(dump.getTime().getSeconds(), dump.getTime().getNanos()));
        return id + "   " + remote + arrow + local + "..." + Instant.now() + "..." + "\r\n" + ByteBufUtil.prettyHexDump(buffer);
    }
}
